#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <stdio.h>
#include <string.h>
#include "led.h"
#include "key.h"
#include "exit.h"
#include "uart.h"
#include "esptimer.h"
#include "gtimer.h"

#define SELECT 0

void app_main(void)
{
    esp_err_t err;
    err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES ||
        err == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ESP_ERROR_CHECK(nvs_flash_init());
    }

#if SELECT == 0
    led_init();
    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(1000));
        LED_TOGGLE();
        printf("LED\n");
    }
#endif

#if SELECT == 1
    led_init();
    boot_key_init();
    uint8_t mode = 0;
    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(10));
        printf("KEY\n");
        switch (boot_key_scan(mode))
        {
        case BOOT_KEY_PRES:
        {
            LED_TOGGLE();
        }
        break;

        default:
            break;
        }
    }
#endif

#if SELECT == 2
    led_init();
    exit_init();
    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(1000));
        printf("EXIT\n");
    }
#endif

#if SELECT == 3
    uint32_t times = 0;
    uint32_t length = 0;
    char data[UART_BUFFER_SIZE] = {0};
    led_init();
    uart_init(115200);

    while (1)
    {
        times++;
        uart_get_buffered_data_len(UART_UX, (size_t *)(&length));
        if (length > 0)
        {
            uart_read_bytes(UART_UX, data, length, 100);
            printf("length:%" PRIu32 "\n", length);
            uart_write_bytes(UART_UX, data, (size_t)strlen(data));
            memset(data, 0, UART_BUFFER_SIZE);
        }
        else
        {
            if (times % 3000 == 0)
            {
                printf("UART TEST\n");
            }
            if (times % 1000 == 0)
            {
                printf("HVP\n");
            }
            if (times % 100 == 0)
            {
                LED_TOGGLE();
            }
        }
        vTaskDelay(pdMS_TO_TICKS(10));
    }
#endif

#if SELECT == 4
    led_init();
    esptimer_init(1000000);
    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(10));
    }
#endif

#if SELECT ==5
    gptimer_event_t g_tim_evente;
    uint8_t record;
    led_init();
    gtimer_init(100,1000000);
    while (1)
    {
        record = 1;

        if (xQueueReceive(queue, &g_tim_evente, 2000))
        {
            ESP_LOGI("GPTIMER_ALARM", "定时器报警, 计数值： %llu", g_tim_evente.event_count);   /* 打印通用定时器发生一次计数事件后获取到的值 */
            record--;
        }
        else
        {
            ESP_LOGW("GPTIMER_ALARM", "错过一次计数事件");
        }
    }
    vQueueDelete(queue);
#endif
}